package br.com.projeto.databases;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.SessionFactory;


public class HibernateFilter implements Filter{

	private SessionFactory session; 
	
	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		try {
			this.session.getCurrentSession().beginTransaction();
			filterChain.doFilter(request, response);
			this.session.getCurrentSession().getTransaction().commit();
			this.session.getCurrentSession().close();
		} catch (Throwable t) {
			try {
				if(this.session.getCurrentSession().getTransaction().isActive()){
					this.session.getCurrentSession().getTransaction().rollback();
				}	
			} catch (Throwable th) {
				th.printStackTrace();
			}
			throw new ServletException();
		}

	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.session = HibernateConfiguration.getSession();
	}

}
